#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(&this->ptimer, SIGNAL(timeout()), this, SLOT(updateTimeAndDisplay()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::updateTimeAndDisplay(){

    QTime current = QTime::currentTime();
    int t = this->baseTime.msecsTo(current);
    QTime showTime(0,0,0,0);
    showTime = showTime.addMSecs(t);
    showStr = showTime.toString("hh:mm:ss:zzz");
    this->ui->lcdNumber->display(showStr);
}

void MainWindow::on_btn_start_clicked()
{
    //一、点击开始计时器变为0：0：0：0（这种方式可优化）
    //this->baseTime.setHMS(0,0,0,0);
    //二、优化后的方法，先获取当前时间
    this->baseTime = QTime::currentTime();
    this->ptimer.start(1);
    //当点击开始的时候让按钮不能再点击
    this->ui->btn_start->setEnabled(false);
    this->ui->btn_stop->setEnabled(true);
    this->ui->btn_pasue->setEnabled(true);
    this->ui->btn_log->setEnabled(true);
}

void MainWindow::on_btn_stop_clicked()
{
    if(this->ui->btn_stop->text() == "停止"){
        this->ui->btn_stop->setText("清零");
        this->ptimer.stop();
        this->ui->btn_pasue->setEnabled(false);
    }else{
        this->ui->lcdNumber->display("00:00:00:000");
        this->ui->textBrowser->clear();
        this->ui->btn_stop->setText("停止");
        //当点击清零后开始按钮又可以点击了
        this->ui->btn_start->setEnabled(true);
        this->ui->btn_pasue->setEnabled(true);
        this->ui->btn_stop->setEnabled(false);
        this->ui->btn_pasue->setEnabled(false);
        this->ui->btn_log->setEnabled(false);
    }

}

void MainWindow::on_btn_pasue_clicked()
{
    static QTime pasueTime;
    if(ui->btn_pasue->text() == "暂停"){
        pasueTime = QTime::currentTime();
        this->ptimer.stop();
        ui->btn_pasue->setText("继续");
        this->ui->btn_stop->setEnabled(false);
    }else{
        QTime cut = QTime::currentTime();
        //获取点击暂停到点击继续之间经历了的时间
        int t = pasueTime.msecsTo(cut);
        //在基准时间上补上这段时间
        this->baseTime = this->baseTime.addMSecs(t);
        this->ptimer.start(1);
        ui->btn_pasue->setText("暂停");
        this->ui->btn_stop->setEnabled(true);
    }
}

void MainWindow::on_btn_log_clicked()
{
    this->ui->textBrowser->append(this->showStr);
}
